package cn.lbaicai.core;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.ModelAttribute;

import com.mysql.fabric.xmlrpc.base.Array;

import cn.lbaicai.common.CurrentUser;
import cn.lbaicai.entity.User;
import cn.lbaicai.entity.Userrole;
import cn.lbaicai.service.RoleUserService;
import cn.lbaicai.utils.AuthUtils;

public class BaseController {
	@Autowired
	public RoleUserService roleUser;
	/**
	 * 设置菜单
	 * @param user
	 * @return
	 * @throws IOException 
	 * @throws JsonMappingException 
	 * @throws JsonParseException 
	 * @throws IllegalArgumentException
	 * @throws FileNotFoundException
	 */
	@SuppressWarnings("unchecked")
	@ModelAttribute("menu")
	public List<Map<String,Object>> getMenus(@CurrentUser User user) throws JsonParseException, JsonMappingException, FileNotFoundException, IOException{
		List<Map<String,Object>> menus = new ArrayList<Map<String,Object>>();
		ObjectMapper objMapper = new ObjectMapper();
		//objMapper.readV
		menus = objMapper.readValue(ResourceUtils.getFile("classpath:menu.json"), new TypeReference<List<Map<String,Object>>>() {});
		List<Userrole> roleUsers = roleUser.selectByUid(user.getId());
		List<String> role = new ArrayList<String>();
		if(roleUsers.size()>0){
			for(Userrole userRole :roleUsers){
				role.add(userRole.getRole().getRoleenname());
			}
		}
		List<Map<String,Object>> resultMenu = new ArrayList<Map<String,Object>>();
		for(Map<String,Object> menu :menus){
			if(AuthUtils.isAuth(role, (String)menu.get("auth"))){
				List<Map<String,Object>> resultSubMenu = new ArrayList<Map<String,Object>>();
				for(Map<String,Object>subMenu:(List<Map<String,Object>>)menu.get("subModule")){
					if(AuthUtils.isAuth(role, (String)subMenu.get("auth"))){
						resultSubMenu.add(subMenu);
					}
				}
				menu.put("subModule", resultSubMenu);
				resultMenu.add(menu);
			}
		}
		return resultMenu;
	}
	/**
	 * 设置公共配置
	 */
	@ModelAttribute()
	public void setParam(@CurrentUser User user,Model model,HttpServletRequest request,HttpServletResponse response){
		model.addAttribute("ctx", request.getContextPath());
	}
}
